package com.lhd.service.qrcode;

import cn.hutool.core.lang.UUID;
import com.lhd.component.RedisComponent;
import com.lhd.entity.dto.AdditionInfoDto;
import com.lhd.entity.enums.ActivityTypeRedisKeyEnum;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Author: liuhd
 * @Date: 2025/5/11 12:27
 * @Description: 刷新二维码服务
 */
@Service
public class RefreshCodeService {

    @Resource
    private RedisComponent redisComponent;

    // 使用线程安全的列表存储待刷新的任务参数
    private final List<RefreshTask> taskList = new CopyOnWriteArrayList<>();

    /**
     * 添加新的刷新任务
     */
    public void handleRefreshCodeTask(List<Integer> aidList, Integer refreshTime) {
        taskList.add(new RefreshTask(aidList, refreshTime));
    }

    /**
     * 定时任务，每秒检查是否有需要执行的刷新任务
     */
    @Scheduled(fixedRate = 2900) // 每秒执行一次
    public void executeRefreshTasks() {
        for (RefreshTask task : taskList) {
            if (task.isStopped()) {
                continue;
            }

//            try {
                UUID uuid = UUID.randomUUID(false);
                AdditionInfoDto additionInfoDto = new AdditionInfoDto();
                additionInfoDto.setQrcode(uuid.toString());

                for (Integer aid : task.aidList) {
                    redisComponent.saveAdditionInfo(additionInfoDto, aid, task.refreshTime, ActivityTypeRedisKeyEnum.QR_CODE_CHECK_IN.getRedisKey());
                }

//                Thread.sleep(task.refreshTime * 1000L); // 按间隔等待

//            } catch (InterruptedException e) {
//                Thread.currentThread().interrupt();
//                task.stop(); // 停止该任务
//            }
        }
    }

    /**
     * 停止某个任务（可选）
     */
    public void stopRefreshTask(List<Integer> aidList) {
        taskList.forEach(task -> {
            if (task.aidList.equals(aidList)) {
                task.stop();
            }
        });
    }

    // 内部类：表示一个刷新任务
    private static class RefreshTask {
        private final List<Integer> aidList;
        private final int refreshTime;
        private final AtomicBoolean stopped = new AtomicBoolean(false);

        public RefreshTask(List<Integer> aidList, int refreshTime) {
            this.aidList = Collections.unmodifiableList(new ArrayList<>(aidList));
            this.refreshTime = refreshTime;
        }

        public boolean isStopped() {
            return stopped.get();
        }

        public void stop() {
            stopped.set(true);
        }
    }
}